package cn.legend.travel.admin.user.controller;

import cn.legend.travel.admin.user.pojo.param.UserUpdateParam;
import cn.legend.travel.admin.user.service.IUserService;
import cn.legend.travel.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;

@Api(tags = "普通用户管理模块")
@RestController
@Validated
@RequiredArgsConstructor
@RequestMapping("users")
public class UserController {
    private final IUserService service;

    @GetMapping("listForAll")
    @ApiOperation("查看所有用户")
    @PreAuthorize("hasAuthority('/users/manage')")
    public JsonResult getAllUsers(Integer pageNum) {
        return JsonResult.ok(service.getAllUsers(pageNum == null ? 1 : pageNum));
    }

    @GetMapping("listForCheck")
    @ApiOperation("查看需要审核的用户")
    @PreAuthorize("hasAuthority('/users/manage')")
    public JsonResult getUsersForCheck(Integer pageNum) {
        return JsonResult.ok(service.getUsersForCheck(pageNum == null ? 1 : pageNum));
    }

    @PostMapping("update")
    @ApiOperation("更改用户账号")
    @PreAuthorize("hasAuthority('/users/manage')")
    public JsonResult update(@RequestBody @Validated UserUpdateParam param) {
        service.update(param);
        return JsonResult.ok();
    }

    @PostMapping("unfreeze")
    @ApiOperation("解除对账号的限制")
    @PreAuthorize("hasAuthority('/users/manage')")
    public JsonResult unfreeze(@RequestParam Long id) {
        service.unfreeze(id);
        return JsonResult.ok();
    }

    @GetMapping("getByUsername")
    @ApiOperation("通过用户名获取用户")
    @PreAuthorize("hasAuthority('/users/manage')")
    public JsonResult getByUsername(@RequestParam String username) {
        return JsonResult.ok(service.getByUsername(username));
    }

    @GetMapping("getByPhone")
    @ApiOperation("通过手机获取用户")
    @PreAuthorize("hasAuthority('/users/manage')")
    public JsonResult getByPhone(@RequestParam @Pattern(regexp = "^1[356789]\\d{9}$", message = "请输入正确的手机格式") String phone) {
        return JsonResult.ok(service.getByPhone(phone));
    }
}
